<?php

use console\db\Migration;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;

/**
 * 用户自定义信息转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000010_t_user_meta_format_data extends Migration {

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $tableName = '{{%user_meta}}';
        $authentTable = '{{%temp_member_detail}}';

        $options = $this->getJoinOptions();

        $on = 'a.id=b.uid';
        $size = count($options);
        $i = 0;
        Console::startProgress($i, $size, 'Updateing objects: ', false);
        foreach ($options as $option) {
            $condition = $on . ArrayHelper::getValue($option, 'condition', '');
            $columns = ArrayHelper::getValue($option, 'columns', []);
            $set = [];
            $tips = '';
            foreach ($columns as $key => $vls) {
                $set[] = $key . '=' . $vls;
                $tips .= $key;
            }
            $sql = "update {$tableName} a inner join {$authentTable} b on {$condition} set " . implode(',', $set);
            $this->db->createCommand($sql)->execute();
            $i++;
            Console::updateProgress($i, $size, $tips);
        }
        Console::endProgress("Extend data update done." . PHP_EOL);
    }

    /**
     * @inheritdoc
     */
    public function getJoinOptions() {
        return [
            [
                'condition' => ' and b.sign is not null',
                'columns' => [
                    'a.signature' => 'b.sign'
                ]
            ],
            [
                'condition' => ' and b.birthday is not null',
                'columns' => [
                    'a.birthday' => 'b.birthday'
                ]
            ],
            [
                'condition' => ' and b.gender>0 and a.gender=0',
                'columns' => [
                    'a.gender' => 'b.gender'
                ]
            ],
            [
                'condition' => '',
                'columns' => [
                    'a.updated_at' => 'b.updatetime'
                ]
            ]
        ];
    }

}
